package com.yytek.nmp.service.impl;


import com.yytek.common.core.constant.Constants;
import com.yytek.common.core.domain.R;
import com.yytek.common.core.utils.StringUtils;
import com.yytek.nmp.domain.IotDeviceInfo;
import com.yytek.nmp.mapper.IotDeviceInfoMapper;
import com.yytek.nmp.mapper.IotProductInfoMapper;
import com.yytek.tddb.api.RemoteTdEngineService;
import com.yytek.tddb.api.domain.Fields;
import com.yytek.tddb.api.domain.SelectDto;
import com.yytek.tddb.api.domain.TableDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class IotDeviceTddbServiceImpl {
    @Autowired
    private RemoteTdEngineService remoteTdEngineService;
    @Autowired
    private IotProductInfoMapper productInfoMapper;
    @Autowired
    private IotDeviceInfoMapper deviceInfoMapper;
    /**
     * 创建设备时序数据库子表
     * @param iotDeviceInfo
     */
    public void createTdDevcieTable(IotDeviceInfo iotDeviceInfo) {
        TableDto tableDto = new TableDto();
        //超级表命名规则 : 产品标识
        //查询产品key
        String productKey = productInfoMapper.selectIotProductInfoById(iotDeviceInfo.getProductId()).getProductKey();
        String superTableName = productKey;
        tableDto.setSuperTableName(superTableName);
        //子表命名规则 : 产品标识_设备标识（设备唯一标识）
        tableDto.setTableName(superTableName + "_" + iotDeviceInfo.getIotId());
        //Tag的处理
        List<Fields> tagsFieldValues = new ArrayList<>();
        // 1:设备所属项目id：projectId
        Fields projectIdTags = new Fields();
        projectIdTags.setFieldValue(iotDeviceInfo.getProjectId());
        tagsFieldValues.add(projectIdTags);
        // 2:设备所属分组id：groupId
        Fields groupIdTags = new Fields();
        groupIdTags.setFieldValue(iotDeviceInfo.getGroupId());
        tagsFieldValues.add(groupIdTags);
        tableDto.setTagsFieldValues(tagsFieldValues);

        R<?> ctResult = remoteTdEngineService.createTable(tableDto);
        if (ctResult.getCode() != 200) {
            log.info("创建时序子表 失败:" + ctResult.getMsg());
        }
    }

    /**
     * 删除设备时序表
     * @param tableName
     */
    public void deleteTable(String tableName) {
        remoteTdEngineService.deleteTable(tableName);
    }

    /**
     * 根据设备id删除设备时序表
     * @param iotId
     */
    public void deleteDeviceTableById(String iotId) {
        String tableName = getTddbDeviceTableName(iotId);
        //删除设备属性历史记录
        deleteTable(tableName);
    }
    /**
     * 获取时序数据库设备子表名称
     * @param iotId
     * @return
     */
    public String getTddbDeviceTableName(String iotId){
        //获取时序数据库表名称
        IotDeviceInfo deviceInfo = deviceInfoMapper.selectIotDeviceInfoByIotId(iotId);
        String productKey = productInfoMapper.selectIotProductInfoById(deviceInfo.getProductId()).getProductKey();
        String tableName = productKey+"_"+ deviceInfo.getIotId();
        return tableName;
    }

    /**
     * 获取设备最新属性值
     * @param id
     * @return
     */
    public List<Map<String, Object>> getPropertiesByIotId(String id) {
        SelectDto selectDto = new SelectDto();
        selectDto.setDataBaseName(Constants.TDDB_DATABASE_NAME);
        //获取设备表名称
        selectDto.setTableName(getTddbDeviceTableName(id));
        //最新一条实时属性值
        R re = remoteTdEngineService.getDataLastOne(selectDto);
        if(re.getCode() == Constants.SUCCESS){
            List<Map<String, Object>> list = (List<Map<String, Object>>) re.getData();
            return list;
        }else{
            throw new RuntimeException(re.getMsg());
        }
    }

    /**
     * 获取设备历史和实时属性值
     *
     * @param id
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public List<Map<String, Object>> getHisProperties(String id, String startTime, String endTime) {
        SelectDto selectDto = new SelectDto();
        selectDto.setDataBaseName(Constants.TDDB_DATABASE_NAME);
        //获取设备表名称
        selectDto.setTableName(getTddbDeviceTableName(id));
        //开始时间戳
        if(StringUtils.isNotEmpty(startTime)){
            selectDto.setStartTime(startTime);
        }
        //结束时间戳
        if(StringUtils.isNotEmpty(endTime)){
            selectDto.setEndTime(endTime);
        }
        //按事件时间戳倒序排序
        selectDto.setOrderBy(" order by event_time desc");
        //属性值
        R re = remoteTdEngineService.getDataByTimestamp(selectDto);
        if(re.getCode() == Constants.SUCCESS){
            List<Map<String, Object>> list = (List<Map<String, Object>>) re.getData();
            return list;
        }else{
            throw new RuntimeException(re.getMsg());
        }

    }
}
